var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var area = require('../../utils/area.js');

var app = getApp()
Page({
  data: { 
    keywrod: '测试',
    searchStatus: true,
    goodsList: [],
    helpKeyword: [],
    historyKeyword: [],
    currentSort: '',  
    currentSortType: 'default',
    currentSortOrder: 'desc',
    filterCategory: [],
    defaultKeyword: {},
    hotKeyword: [],
    page: 1,
    limit: 10,  
    allBrandList: [],
    brandIndex:0,
    allCategoryList: [],
    categoryIndex:0,
    currentCategoryList: [],
    dealTypeList:[],
    dealIndex:0,
    optionsBrandId:0,
    optionsCategoryId:0,
    openSelectRegion: false,
    regionType: 1,
    regionList: [],
    selectRegionDone: false,
    address: {
      id: 0,
      areaCode: 0,
      address: '',
      name: '',
      tel: '',
      isDefault: 0,
      province: '',
      city: '',
      county: ''
    },
    addressId: 0,
    selectRegionList: [{
      code: 0,
      name: '省份'
    },
    {
      code: 0,
      name: '城市'
    },
    {
      code: 0,
      name: '区县'
    }]
  },  
  //事件处理函数
  closeSearch: function() {
    wx.navigateBack()
  },

  clearKeyword: function() {
    this.setData({
      keyword: '',
      searchStatus: false
    });
  },
  onLoad: function(options) {
    if(options.brandId>0){
      // 根据品牌去查询
      this.setData({
        optionsBrandId: parseInt(options.brandId)
      });
    }else if(options.categoryId>0){
      // 根据分类 查询
      this.setData({
        optionsCategoryId: parseInt(options.categoryId)
      });
    } 
    this.getSearchKeyword();
  },
  onReady: function() {
    wx.showLoading({
      title: '加载中...',
    });
    this.getBrandCategoryList();  
  },
  getBrandCategoryList: function() {
    let that = this;
    let _optionsBrandId = that.data.optionsBrandId;
    let _optionsCategoryId = that.data.optionsCategoryId;
    var _brandIndex = 0;
    var _categoryIndex = 0;
    var _currentCategoryList = [];
    var categoryObj = {
      id:0,
      brandId:0,
      categoryName:"车型"
    } 
    _currentCategoryList.push(categoryObj); 
    
    var _dealTypeList = this.data.dealTypeList;
    var dealObj0 = {
        name:"类型",
        dealType:0
    } 
    _dealTypeList.push(dealObj0);
    var dealObj1 = {
      name:"出售",
      dealType:1
    }
    _dealTypeList.push(dealObj1);
    var dealObj2 = {
      name:"收购",  
      dealType:2
    }
    _dealTypeList.push(dealObj2);

    util.request(api.GetBrandCategoryList).then(function(res) {
      if (res.code === 200) {
        var _allBrandList = res.dataObject.allBrandList;
        var _allCategoryList = res.dataObject.allCategoryList;
        if(_optionsCategoryId>0){
          console.log("分类查询");  
          console.log(_optionsCategoryId);

          // 获得品牌id
          for (let index = 0; index < _allCategoryList.length; index++) {
            const element = _allCategoryList[index];
            if(element.id==_optionsCategoryId){
              _optionsBrandId = element.brandId;
            }
          }
        }
        if(_optionsBrandId>0){
          console.log("品牌查询");
          console.log(_optionsBrandId);
          for (let index = 0; index < _allBrandList.length; index++) {
            const element = _allBrandList[index];
            if(element.id==_optionsBrandId){  
              _brandIndex = index;
              break;
            }
          }
         
          // 封装这个品牌下所有的分类
          for (let index = 0; index < _allCategoryList.length; index++) {
            const element = _allCategoryList[index];
            if(element.brandId==_optionsBrandId){
              _currentCategoryList.push(element);
            }
          }
        }

        if(_optionsCategoryId>0){
          // 得到分类的  索引
          for (let index = 0; index < _currentCategoryList.length; index++) {
            const element = _currentCategoryList[index];
            if(element.id==_optionsCategoryId){
              _categoryIndex = index;
              break;
            }
          }
        }

        that.setData({
          allBrandList: _allBrandList,
          allCategoryList: _allCategoryList,
          currentCategoryList:_currentCategoryList,
          dealTypeList:_dealTypeList,
          categoryIndex:_categoryIndex,
          brandIndex:_brandIndex,
        });

        if(_categoryIndex > 0||_brandIndex > 0){
          that.getGoodsList();
        } 
      }
      wx.hideLoading();
    });
  },
  bindBrandPickerChange: function(e) {
    
    let _allCategoryList = this.data.allCategoryList;
    // 当前品牌索引 
    let _brandIndex = e.detail.value;
    // 得到品牌id
    let _brandId = this.data.allBrandList[_brandIndex].id;

    var _currentCategoryList = [];
    var categoryObj = {
      id:0,
      brandId:0,
      categoryName:"车型" 
    }  
    _currentCategoryList.push(categoryObj);
    for (let idex = 0; idex < _allCategoryList.length; idex++) {
      const element = _allCategoryList[idex];
      if(element.brandId==_brandId){
        _currentCategoryList.push(element);
      }
    }

    this.setData({
      brandIndex: _brandIndex,
      currentCategoryList:_currentCategoryList,
      categoryIndex: 0,
    });
    // 查询
    this.getGoodsList();
  },  
  bindCategoryPickerChange: function(e) {
    this.setData({
      categoryIndex: e.detail.value,
    });
    // 查询
    this.getGoodsList();
  },
  bindDealTypePickerChange: function(e) {
    this.setData({  
      dealIndex: e.detail.value,
    });
    // 查询
    this.getGoodsList();
  },

  getSearchKeyword() {
    let that = this;
    // util.request(api.SearchIndex).then(function(res) {
    //   if (res.errno === 0) {
    //     that.setData({
    //       historyKeyword: res.data.historyKeywordList,
    //       defaultKeyword: res.data.defaultKeyword,
    //       hotKeyword: res.data.hotKeywordList
    //     });
    //   }
    // });
  },

  inputChange: function(e) {
    if(e.detail.value.length>0){
      this.setData({
        keyword: e.detail.value,
        searchStatus: false
      });
    }else{
      this.setData({
        keyword: "",
        searchStatus: true
      });
    }
    // if (e.detail.value) {
    //   this.getHelpKeyword();
    // }
  },
  getHelpKeyword: function() {
    let that = this;
    // util.request(api.SearchHelper, {
    //   keyword: that.data.keyword
    // }).then(function(res) {
    //   if (res.errno === 0) {
    //     that.setData({
    //       helpKeyword: res.data
    //     });
    //   }
    // });
  },
  inputFocus: function() {
    let that = this;
    
    // if (that.data.keyword) {
    //   that.getHelpKeyword();
    // }
  },
  clearHistory: function() {
    this.setData({
      historyKeyword: []
    })

    util.request(api.SearchClearHistory, {}, 'POST')
      .then(function(res) {
        console.log('清除成功');
    });
  },
  getGoodsList: function() {
    let that = this; 
    var _address = that.data.address;
    console.log(_address);
    var _province = "";
    var _city = "";
    var _county = "";
    if(_address.province){
      _province = _address.province;
    }
    if(_address.city){
      _city = _address.city;
    } 
    if(_address.county){
      _county = _address.county;
    }

    let _brandIndex = that.data.brandIndex;
    let _categoryIndex = that.data.categoryIndex;
    let _dealIndex = that.data.dealIndex;
    util.request(api.SearchProductList, {
      keyword: that.data.keyword,
      currentPage: that.data.page,
      pageSize: that.data.limit,
      sort: that.data.currentSort,
      sortType: that.data.currentSortOrder,
      brandId:that.data.allBrandList[_brandIndex].id, 
      categoryId:that.data.currentCategoryList[_categoryIndex].id,
      dealType:that.data.dealTypeList[_dealIndex].dealType,
      province:_province,
      city:_city,
      district:_county,
    }).then(function(res) { 
      if (res.code === 200) {
        that.setData({  
          searchStatus: true,
          goodsList: res.dataObject,
        });
      } 
      //重新获取关键词
      //that.getSearchKeyword();
    });
  },  
  onKeywordTap: function(event) {
    this.getSearchResult(event.target.dataset.keyword);
  },
  getSearchResult(keyword) {
    if (keyword === '') {
      keyword = this.data.defaultKeyword.keyword;
    }
    this.setData({
      keyword: keyword,
      page: 1,
      goodsList: []
    });
    this.getGoodsList();
  },
  openSortFilter: function(e) {
    let that = this;
    
    let currentId = e.currentTarget.id;
    switch (currentId) {
      case 'priceSort':
        let tmpSortOrder = 'asc';
        if (that.data.currentSortOrder == 'asc') {
          tmpSortOrder = 'desc';
        } 
        that.setData({
          currentSortType: 'price',
          currentSort: 'current_price',
          currentSortOrder: tmpSortOrder
        });
        that.getGoodsList();
        break;
      default:
        //综合排序
        that.setData({
          currentSortType: 'default',
          currentSort: '',  
          currentSortOrder: '',
        }); 
        that.getGoodsList();
    }
  },
  onKeywordConfirm(e) { 
    this.getSearchResult(e.detail.value);
  },
  setRegionDoneStatus() {
    let that = this;
    let doneStatus = that.data.selectRegionList.every(item => {
      return item.code != 0;
    });
    that.setData({
      selectRegionDone: doneStatus
    })
  },
  chooseRegion() {
    let that = this;
    this.setData({
      openSelectRegion: !this.data.openSelectRegion
    });

    //设置区域选择数据
    let address = this.data.address;
    if (address.areaCode > 0) {
      let selectRegionList = this.data.selectRegionList;
      selectRegionList[0].code = address.areaCode.slice(0, 2) + '0000';
      selectRegionList[0].name = address.province;

      selectRegionList[1].code = address.areaCode.slice(0, 4) + '00';
      selectRegionList[1].name = address.city;

      selectRegionList[2].code = address.areaCode;
      selectRegionList[2].name = address.county;

      let regionList = area.getList('county', address.areaCode.slice(0, 4));
      regionList = regionList.map(item => {
        //标记已选择的
        if (address.areaCode === item.code) {
          item.selected = true;
        } else {
          item.selected = false;
        }
        return item;
      })

      this.setData({
        selectRegionList: selectRegionList,
        regionType: 3,
        regionList: regionList
      });

    } else {  
      let selectRegionList = [{
            code: 0,
            name: '省份',
          },
          {
            code: 0,
            name: '城市',
          },
          {
            code: 0,
            name: '区县',
          }
        ];

      this.setData({
        selectRegionList: selectRegionList,
        regionType: 1,
        regionList: area.getList('province')
      });
    }
    this.setRegionDoneStatus();
  },
  selectRegionType(event) {
    let that = this;
    let regionTypeIndex = event.target.dataset.regionTypeIndex;
    let selectRegionList = that.data.selectRegionList;

    //判断是否可点击
    if (regionTypeIndex + 1 == this.data.regionType || (regionTypeIndex - 1 >= 0 && selectRegionList[regionTypeIndex - 1].code <= 0)) {
      return false;
    }

    let selectRegionItem = selectRegionList[regionTypeIndex];
    let code = selectRegionItem.code;
    let regionList;
    if (regionTypeIndex === 0) {
      // 点击省级，取省级
      regionList = area.getList('province');
    }
    else if (regionTypeIndex === 1) {
      // 点击市级，取市级
      regionList = area.getList('city', code.slice(0, 2)); 
    }
    else{
      // 点击县级，取县级
      regionList = area.getList('county', code.slice(0, 4)); 
    }

    regionList = regionList.map(item => {
      //标记已选择的
      if (that.data.selectRegionList[regionTypeIndex].code == item.code) {
        item.selected = true;
      } else {
        item.selected = false;
      }
      return item;
    })

    this.setData({
      regionList: regionList,
      regionType: regionTypeIndex + 1
    })

    this.setRegionDoneStatus();
  },
  selectRegion(event) {
    let that = this;
    let regionIndex = event.target.dataset.regionIndex;
    let regionItem = this.data.regionList[regionIndex];
    let regionType = this.data.regionType;
    let selectRegionList = this.data.selectRegionList;
    selectRegionList[regionType - 1] = regionItem;

    if (regionType == 3) {
      this.setData({
        selectRegionList: selectRegionList
      })

      let regionList = that.data.regionList.map(item => {
        //标记已选择的
        if (that.data.selectRegionList[that.data.regionType - 1].code == item.code) {
          item.selected = true;
        } else {
          item.selected = false;
        }
        return item;
      })

      this.setData({
        regionList: regionList
      })

      this.setRegionDoneStatus();
      return
    }

    //重置下级区域为空
    selectRegionList.map((item, index) => {
      if (index > regionType - 1) {
        item.code = 0;
        item.name = index == 1 ? '城市' : '区县';
      }
      return item;
    });

    this.setData({
      selectRegionList: selectRegionList,
      regionType: regionType + 1
    })
    
    let code = regionItem.code;
    let regionList = [];
    if (regionType === 1) {
      // 点击省级，取市级
      regionList= area.getList('city', code.slice(0, 2))
    }
    else {
      // 点击市级，取县级
      regionList= area.getList('county', code.slice(0, 4))
    }

    this.setData({
      regionList: regionList
    })

    this.setRegionDoneStatus();
  },
  // 确定
  doneSelectRegion() {
    // if (this.data.selectRegionDone === false) {
    //   return false;
    // }
    let address = this.data.address;
    let selectRegionList = this.data.selectRegionList;
    var _province = selectRegionList[0].name;
    if(_province=="省份"){
      _province = "";
    }
    var _city = selectRegionList[1].name;
    if(_city=="城市"){
      _city = "";
    }
    var _county = selectRegionList[2].name;
    if(_county=="区县"){
      _county = "";
    } 
    address.province = _province;
    address.city = _city;
    address.county = _county; 
    address.areaCode = selectRegionList[2].code;
    this.setData({
      address: address,
      openSelectRegion: false
    });

    this.getGoodsList();
  },
  // 取消
  cancelSelectRegion() {
    this.setData({
      openSelectRegion: false,
      regionType: this.data.regionDoneStatus ? 3 : 1
    });
  },
})